#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <wiringPi.h>

#include "types.h"

#include "i2c_protocol.h"

#define I2C_ADDR		0x80
#define I2C_SDA			(3)
#define I2C_SCL			(21)
#define HUMI_HOLD_MASTER    0xE5
#define TEMP_HOLD_MASTER    0xE3

void *malloc_instead(uint32 size)
{
	return malloc(size);
}

int free_insead(void *ptr)
{
	free(ptr);
	return 1;
}

int delay_us_insead(uint32 us)
{
	delayMicroseconds(us);
	return 1;
}

int delay_ms_insead(uint32 ms)
{
	delay(ms);
	return 1;
}

int gpio_set_direction(int gpio, uint8 direction)
{
	pinMode(gpio, direction);
	return 1;
}

int gpio_set_level(int gpio, uint8 value)
{
	digitalWrite(gpio, value);
	return 1;
}

int gpio_get_level(int gpio)
{
	return digitalRead(gpio);
}

int main(void)
{
	i2c_callback cb = {0};
	i2c_gpio gpio_handle = {0};
	uint8 send_data = TEMP_HOLD_MASTER;
	uint8 read_data[2] = {0};
	uint16 temp = 0;
	uint16 humi = 0;

	cb.delay = delay_us_insead;
	cb.malloc = malloc_instead;
	cb.free = free_insead;
	cb.set_gpio_direction = gpio_set_direction;
	cb.set_gpio_level = gpio_set_level;
	cb.get_gpio_level = gpio_get_level;
	cb.set_gpio_pullupdn = pullUpDnControl;

	gpio_handle.gpio_scl = I2C_SCL;
	gpio_handle.gpio_sda = I2C_SDA;

	wiringPiSetup();

	i2c_init(&gpio_handle, &cb, LOG_ERROR);

	while(1)
	{
		send_data = TEMP_HOLD_MASTER;
		i2c_send_buf(I2C_ADDR, &send_data, 1);
		delay_ms_insead(200);
		i2c_read_buf(I2C_ADDR, read_data, 2);
		temp = 0;
		temp |= read_data[0] << 8;
		temp += read_data[1];

		printf("read_data[0] = 0x%02x, read_data[1] = 0x%02x\n", read_data[0], read_data[1]);
		printf("This temp = %f\n", temp*175.72/65536-46.85);
		sleep(2);

		send_data = HUMI_HOLD_MASTER;
		i2c_send_buf(I2C_ADDR, &send_data, 1);
		delay_ms_insead(200);
		i2c_read_buf(I2C_ADDR, read_data, 2);
		humi = 0;
		humi |= read_data[0] << 8;
		humi += read_data[1];

		printf("read_data[0] = 0x%02x, read_data[1] = 0x%02x\n", read_data[0], read_data[1]);
		printf("This humidity = %f\n", ((float)humi)*125/65536-6);
		sleep(2);
		//reset
		send_data = 0xFE;
		i2c_send_buf(I2C_ADDR, &send_data, 1);
		sleep(2);
	}
	i2c_deinit();
	return 1;
}
